package com.ygxsk.carhome.ui.leads;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventCarEvaluateMain;
import com.ygxsk.carhome.event.EventLeadDetail;
import com.ygxsk.carhome.event.EventRepariMain;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.EvaluteCurrentItemBean;
import com.ygxsk.carhome.response.LeadListItemBean;
import com.ygxsk.carhome.response.RepairManageItemBean;
import com.ygxsk.carhome.response.RunManGroupHeadOrTeamCheck;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusRunManGroupHeadMan;
import com.ygxsk.carhome.rxbus.RxBusRunManGroupHeadOrTeamCheck;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.RunManGroupHeadManMemberAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-13  15:54
 * @Description:人员管理页面
 */
public class LeadManagerGroupActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshlayoutingroupheadman)
    SmartRefreshLayout refreshLayoutInGroupHeadMan;

    @BindView(R.id.recyclerviewingroupheadman)
    RecyclerView recyclerViewInGroupHeadMan;

    //点击确定的按钮
    @BindView(R.id.roundbuttonsuregroupheadman)
    RoundTextView roundButtonSureGroupHeadMan;

    private ArrayList<RunManGroupHeadOrTeamCheck> mDatasResources = new ArrayList<>();
    private RunManGroupHeadManMemberAdapter runManGroupHeadManMemberAdapter;

    //从哪里过来
    private int extra_jumpfrom_where;
    //携带从列表过来的,直接携带过去,主要是为了获取 人员列表的类型
    private LeadListItemBean extra_lead_list_item_bean;

    //添加 是车辆评估的 这条数据携带
    private EvaluteCurrentItemBean extra_evalute_current_item_bean;

    //预约维保 获取销售人员列表--售后人员列表
    private RepairManageItemBean extra_repair_manage_item_bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        processExtraData();

        initloading();

        initViews();

        // TODO: 2023-07-14 14:47 真实开发放开


        gainDatas();


    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_lead_manager_group;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//      toolbarHelper.setTitle(getString(R.string.choose_sell_person));
        toolbarHelper.setTitle(getString(R.string.choose_sell_person_other));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());

        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {
        gainDatas();
    }

    @Override
    protected void initViews() {

        runManGroupHeadManMemberAdapter = new RunManGroupHeadManMemberAdapter(R.layout.groupmemberheadmanadapter, mDatasResources);
        recyclerViewInGroupHeadMan.setLayoutManager(new MyLinearLayoutManager(this));
        recyclerViewInGroupHeadMan.clearAnimation();
        recyclerViewInGroupHeadMan.setAdapter(runManGroupHeadManMemberAdapter);
        runManGroupHeadManMemberAdapter.notifyDataSetChanged();

        runManGroupHeadManMemberAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                RunManGroupHeadOrTeamCheck runManGroupHeadOrTeamCheck = (RunManGroupHeadOrTeamCheck) adapter.getItem(position);

                CheckBox checkBoxInHeadMan = (CheckBox) view.findViewById(R.id.checkboxinheadman);
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "点击了条目内容" + runManGroupHeadOrTeamCheck.getGroupUserName());

                if (runManGroupHeadOrTeamCheck != null) {

                    int isChecked = runManGroupHeadOrTeamCheck.getIsChecked();

                    if (isChecked == 0) {

                        for (int index = 0; index < mDatasResources.size(); index++) {

                            if (index == position) {
                                mDatasResources.get(index).setIsChecked(1);
                                checkBoxInHeadMan.setChecked(true);
                            } else {
                                mDatasResources.get(index).setIsChecked(0);
                                checkBoxInHeadMan.setChecked(false);
                            }

                        }

                    } else if (isChecked == 1) {//如果当前状态是已经被选中的状态

                        //全部置空
                        for (int ind = 0; ind < mDatasResources.size(); ind++) {
                            mDatasResources.get(ind).setIsChecked(0);
                            checkBoxInHeadMan.setChecked(false);
                        }

                    }

                    if (runManGroupHeadManMemberAdapter != null) {
                        runManGroupHeadManMemberAdapter.notifyDataSetChanged();
                    }

                }

            }
        });


        //暂时设置 仅仅只有下拉刷新，没有加载更多；
        refreshLayoutInGroupHeadMan.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDatasResources != null && !mDatasResources.isEmpty()) {
                            mDatasResources.clear();
                        }

                        if (runManGroupHeadManMemberAdapter != null) {
                            runManGroupHeadManMemberAdapter.notifyDataSetChanged();
                        }

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

        //点击【确定】勾选完毕 销售人员
        roundButtonSureGroupHeadMan.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {

                RxBusRunManGroupHeadMan rxBusRunManGroupHeadMan = new RxBusRunManGroupHeadMan(ExtraValue.RXBUS_RUNMANGROUP_HEADMAN);

                for (RunManGroupHeadOrTeamCheck runManGroupHeadOrTeamChecked : mDatasResources) {
                    if (runManGroupHeadOrTeamChecked.getIsChecked() == 1) {
                        rxBusRunManGroupHeadMan.setRunManGroupHeadOrTeamCheck(runManGroupHeadOrTeamChecked);
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + runManGroupHeadOrTeamChecked.getTrueName());
                    }
                }

                //拦截
                if (ObjectUtils.isEmpty(rxBusRunManGroupHeadMan.getRunManGroupHeadOrTeamCheck())) {
                    ToastUtils.showShort(R.string.choose_person);
                    return;
                }

//                RxBus.getInstance().post(rxBusRunManGroupHeadMan);


                //2023年10月27日11:21:48 新修改逻辑
                if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_SIGNATURE_ADDSUBMIT_ACTIVITY) {

                    //如果是从【新车销售的 法大大电子签章 签约合同页过来的】
                    method_gainAssignPerson_upLoad_forSignatureAddSubmit(rxBusRunManGroupHeadMan.getRunManGroupHeadOrTeamCheck());

                } else {

                    //只有一个单个点击
                    CommUtils.checkDialog(mAlertView);

                    String messageContent = StringUtils.getString(R.string.clearaddorsubmithalf) +
                            "【" + rxBusRunManGroupHeadMan.getRunManGroupHeadOrTeamCheck().getTrueName() + "】";

                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            messageContent,//提示内容，确定提交吗？
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                //如果是从【车辆评估】模块过来的
                                if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_EVALUATE_DETAIL_ACTIVITY) {

                                    method_gainAssignPerson_upLoad_forEvaluate(rxBusRunManGroupHeadMan.getRunManGroupHeadOrTeamCheck());

                                } else if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_REPAIR_DETAIL_ACTIVITY) {

                                    method_gainAssignPerson_upLoad_forBookingRepair(rxBusRunManGroupHeadMan.getRunManGroupHeadOrTeamCheck());

                                } else {
                                    //这是 【潜在客户】分配接口
                                    method_gainAssignPerson_upLoad(rxBusRunManGroupHeadMan.getRunManGroupHeadOrTeamCheck());
                                }
                            }

                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                }

            }
        });


        //        refreshLayoutInGroupHeadMan.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
//
//            @Override
//            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//
//                refreshLayout.getLayout().post(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        refreshLayout.finishRefresh();
//
//                    }
//                });
//
//            }
//
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//
//                refreshLayout.getLayout().post(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        refreshLayout.finishLoadMore();
//
//                    }
//                });
//
//            }
//
//
//        });

    }

    @Override
    protected void gainDatas() {

        if (mDatasResources != null && !mDatasResources.isEmpty()) {
            mDatasResources.clear();
        }

        if (NetworkUtils.isConnected()) {

            if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_EVALUATE_DETAIL_ACTIVITY) {

                //为了获取【车辆评估】的二手车销售
                getServerDatas_evaluate();

            } else if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_REPAIR_DETAIL_ACTIVITY) {

                //为了获取【车辆评估】的二手车销售
                getServerDatas_bookingRepair();

            } else if (extra_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_SIGNATURE_ADDSUBMIT_ACTIVITY) {

                getServerDatas_signatureAddSubmit();

            } else {
                getServerDatas();

            }

        } else {
            netWorkError();
        }

    }

    //选中经理人的提交给预约申请页面
    private void method_gainAssignPerson_upLoad_forSignatureAddSubmit(RunManGroupHeadOrTeamCheck _runManGroupHeadOrTeamCheck) {

        //这里是员工的二维码信息
        RxBusRunManGroupHeadOrTeamCheck rxBusRunManGroupHeadOrTeamCheck = new RxBusRunManGroupHeadOrTeamCheck(ExtraValue.RXBUS_RUNMANGROUP_TEAMMAN);
        rxBusRunManGroupHeadOrTeamCheck.setRunManGroupHeadOrTeamCheck(_runManGroupHeadOrTeamCheck);
        RxBus.getInstance().post(rxBusRunManGroupHeadOrTeamCheck);

        //关闭该页面内容
        methodBack();

    }

    //获取预约维保的 销售 售后的人员 提交信息；
    private void method_gainAssignPerson_upLoad_forBookingRepair(RunManGroupHeadOrTeamCheck _runManGroupHeadOrTeamCheck) {

        HashMap<String, Object> map = new HashMap<>();
        //hashMapParameter.put(Parameterkey.spaceIds, tagSpaceIdsPass.toString().replace("[", "").replace("]", ""));
        map.put(Parameterkey.managerId, _runManGroupHeadOrTeamCheck.getCustomerId());//员工ID
        map.put(Parameterkey.appointmentId, extra_repair_manage_item_bean.getAppointmentId());//预约维保单id

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEFORDELIVERY);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateForDelivery_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateForDelivery(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String value) throws Throwable {

                        //刷新详情页，并且这个页面关闭
                        EventRepariMain eventRepariMain = new EventRepariMain();
                        eventRepariMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_REPAIR_MAIN_LIST);
                        EventBus.getDefault().post(eventRepariMain);

                        methodSubmitSuccess(LeadManagerGroupActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                methodBack();

                            }
                        });

                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException apiException) {
                        //
                    }
                });


    }

    //【车辆评估】的分配人员列表
    private void method_gainAssignPerson_upLoad_forEvaluate(RunManGroupHeadOrTeamCheck _runManGroupHeadOrTeamCheck) {

        HashMap<String, Object> map = new HashMap<>();
        //hashMapParameter.put(Parameterkey.spaceIds, tagSpaceIdsPass.toString().replace("[", "").replace("]", ""));

        ArrayList<String> tempList = new ArrayList<>();
        tempList.add(extra_evalute_current_item_bean.getEstimateId());

        //map.put(Parameterkey.ids, tempList.toString().replace("[", "").replace("]", ""));//车辆评估的这条数据的id
        map.put(Parameterkey.ids, tempList);//车辆评估的这条数据的id
        map.put(Parameterkey.receptionId, _runManGroupHeadOrTeamCheck.getCustomerId());//员工的id
        map.put(Parameterkey.receptionName, _runManGroupHeadOrTeamCheck.getTrueName());//员工的姓名

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATERECEPTIONBYIDS);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateReceptionByIds_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateReceptionByIds(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String value) throws Throwable {

                        methodSubmitSuccess(LeadManagerGroupActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                //刷新详情页，并且这个页面关闭
                                EventCarEvaluateMain eventCarEvaluateMain = new EventCarEvaluateMain();
                                eventCarEvaluateMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_EVALUATE_CAR_LIST);
                                EventBus.getDefault().post(eventCarEvaluateMain);

                                methodBack();

                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    private void method_gainAssignPerson_upLoad(RunManGroupHeadOrTeamCheck _runManGroupHeadOrTeamCheck) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.latentCustomerId, extra_lead_list_item_bean.getLatentCustomerId());//该潜客信息,潜客记录，的id
        map.put(Parameterkey.receptionId, _runManGroupHeadOrTeamCheck.getCustomerId());//员工的id
        map.put(Parameterkey.receptionName, _runManGroupHeadOrTeamCheck.getTrueName());//员工的姓名

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATERECEPTION_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateReception_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateReception(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String value) throws Throwable {

                        methodSubmitSuccess(LeadManagerGroupActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                //刷新详情页，并且这个页面关闭
                                EventLeadDetail eventLeadDetail = new EventLeadDetail();
                                eventLeadDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_LEAD_DETAIL);
                                EventBus.getDefault().post(eventLeadDetail);

                                methodBack();

                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });

    }

    //获取人员列表信息
    private void getServerDatas() {
//        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());

        map.put(Parameterkey.saleType, extra_lead_list_item_bean.getLatentType());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETSALEINFOLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getSaleInfoList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getSaleInfoList(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        // TODO: 2023-08-10 15:51 空数据处理

                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    //获取合同签约的 销售人员，这里是全部的员工？还是仅仅是销售人员
    private void getServerDatas_signatureAddSubmit() {

        //        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//      map.put(Parameterkey.vehicleType, 1);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERLISTBYSHOP_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerListByShop_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerListByShop(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        //填充列表
                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        if (apiException != null) {
                            ToastUtils.showShort(apiException.getDisplayMessage());
                        }

                    }
                });


    }

    //获取预约维保的获取销售人员列表接口
    private void getServerDatas_bookingRepair() {

        //        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.saleType, "3");

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETSALEINFOLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getSaleInfoList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getSaleInfoList(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    //车辆评估的获取销售人员列表，这里主要是获取 二手车销售："saleType": 1 //类别：1新车销售；2二手车销售；3售后

    private void getServerDatas_evaluate() {
//        {
//                "shopInfoId": 1495,
//                "saleType": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.saleType, "2");

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETSALEINFOLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getSaleInfoList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getSaleInfoList(RequestBody.create(JSON.toJSONString(map,//
                                SerializerFeature.PrettyFormat, //
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(LeadManagerGroupActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<ArrayList<RunManGroupHeadOrTeamCheck>>() {
                    @Override
                    public void accept(ArrayList<RunManGroupHeadOrTeamCheck> runManGroupHeadOrTeamCheckArrayList) throws Throwable {

                        methodHandlerSuccess(runManGroupHeadOrTeamCheckArrayList);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });


    }

    private void methodHandlerSuccess(ArrayList<RunManGroupHeadOrTeamCheck> _runManGroupHeadOrTeamCheckArrayList) {

        if (_runManGroupHeadOrTeamCheckArrayList != null && !_runManGroupHeadOrTeamCheckArrayList.isEmpty()) {

            if (mDatasResources != null) {
                mDatasResources.addAll(_runManGroupHeadOrTeamCheckArrayList);
            }
            //先判断外侧，是不是为空，为空就是新进入添加，不是空，就是有历史记录的

        } else {
            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
        }

        if (runManGroupHeadManMemberAdapter != null) {
            runManGroupHeadManMemberAdapter.notifyDataSetChanged();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

//        if (!TextUtils.isEmpty(extra_runmangroup_headman_teamleaderid)) {
//            extra_runmangroup_headman_teamleaderid = "";
//        }

        if (mDatasResources != null && !mDatasResources.isEmpty()) {

            mDatasResources.clear();

            if (runManGroupHeadManMemberAdapter != null) {
                runManGroupHeadManMemberAdapter.notifyDataSetChanged();
                runManGroupHeadManMemberAdapter = null;
            }

            mDatasResources = null;
        }

    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }


    @Override
    public void processExtraData() {

        //页面跳转传值bundle
        Bundle bundle = this.getIntent().getExtras();

        //use the data received here
        if (bundle != null) {

            //判断父亲入口是从哪里 进来的，是【新增小组】还是【修改小组】，修改小组不用传递groupid
            extra_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            //携带潜客的部分信息，用来确认  //类别：1新车销售；2二手车销售；3售后
            extra_lead_list_item_bean = bundle.getParcelable(ExtraKey.EXTRA_LEAD_LIST_ITEM_BEAN);

            extra_evalute_current_item_bean = bundle.getParcelable(ExtraKey.EXTRA_EVALUTE_CURRENT_ITEM_BEAN);

            extra_repair_manage_item_bean = bundle.getParcelable(ExtraKey.EXTRA_REPAIR_MANAGE_ITEM_BEAN);

            //如果是修改小组，那么传递小组的id过来；
//            groupId_upLoad = bundle.getString(ExtraKey.EXTRA_RUNMANGROUP_GROUP_ID);//EXTRA_RUNMANGROUP_GROUP_ID

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL+"extra_jumpfrom_where-->"+extra_jumpfrom_where+"--groupId_upLoad-->"+groupId_upLoad);

            //处理携带的所属县域id,用来查询这个县域的小组长，
//            extra_runmangroup_countydeptid_upload = bundle.getString(ExtraKey.EXTRA_RUNMANGROUP_COUNTYDEPTID_UPLOAD);

            //处理携带data
//            extra_runmangroup_headman_teamleaderid = bundle.getString(ExtraKey.EXTRA_RUNMANGROUP_HEADMAN_TEAMLEADERID);

        }


    }
}